#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ = '__Jack__'

from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import sessionmaker
from config.config import CFG
from log import log
from urllib.parse import quote_plus as urlquote
from sqlalchemy import event

cfg = CFG().cfg
db = cfg.db
if CFG.env != 'prod':
    log.info(f"database.py: {cfg}")
    print(db.type, db.server, db.username, db.password)

echo_enable = True if CFG.env != 'prod' else False

if db.type == "mssql":
    log.info('mssql is running!')
    engine = create_engine(f'mssql+pymssql://{db.username}:{urlquote(db.password)}@{db.server}/{db.database}?charset=utf8', echo=echo_enable)
elif db.type == "mysql":
    log.info('mysql is running!')
    engine = create_engine(f'mysql+pymysql://{db.username}:{urlquote(db.password)}@{db.server}/{db.database}?charset=utf8', echo=echo_enable)
else:
    SQLALCHEMY_DATABASE_URL = f'sqlite:///./sqlite/{db.database}.sqlite3'
    engine = create_engine(
        # echo=True表示引擎将用repr()函数记录所有语句及其参数列表到日志
        # 由于SQLAlchemy是多线程，指定check_same_thread=False来让建立的对象任意线程都可使用。这个参数只在用SQLite数据库时设置
        SQLALCHEMY_DATABASE_URL, echo=True, connect_args={'check_same_thread': False}
    )
# SQLALCHEMY_DATABASE_URL = "postgresql://username:password@host:port/database_name"  # MySQL或PostgreSQL的连接方法

# 在SQLAlchemy中，CRUD都是通过会话(session)进行的，所以我们必须要先创建会话，每一个SessionLocal实例就是一个数据库session
# flush()是指发送数据库语句到数据库，但数据库不一定执行写入磁盘；commit()是指提交事务，将变更保存到数据库文件
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=True)


class SqlBase(DeclarativeBase):
    pass


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

